/*
 *      Copyright: Bernd Schubert <bschubert@ddn.com>
 *      License: GPLv3
*/


#include <stdio.h>
#include <string.h>
#include <stdint.h>
#include <errno.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdbool.h>
#include "sd.h"
#include "hash.h"

static struct mdt_dentry_hash *mdt_hash = NULL;
static struct ost_fid_hash *ost_hash = NULL;

/**
 * Add a MDT dentry
 */
void hash_add_dentry(dentry_t *dentry)
{
	struct mdt_dentry_hash *sde; // a single sh_hash entry
	sde = malloc(sizeof(struct mdt_dentry_hash));
	if (sde == NULL) {
		fprintf(stderr, "malloc of mdt_hash entry failed: %s\n",
			strerror(errno));
	}
	sde->inode = dentry->inode;
	sde->dentry = dentry;

	HASH_ADD_INT(mdt_hash, inode, sde);
}

/**
 * Find MDT dentry
 */
dentry_t *hash_find_dentry(uint64_t inode)
{
	if (!mdt_hash) 
		return NULL;

	struct mdt_dentry_hash *sde; // a single mdt hash entry

	HASH_FIND_INT(mdt_hash, &inode, sde);
	if (sde == NULL) 
		return NULL;

	return sde->dentry;
}

/**
 * Add OST file-id
 */
void hash_add_fid(struct ost_fid *ost_fid)
{
	struct ost_fid_hash *ohe; // ost hash entry
	ohe = malloc(sizeof(struct ost_fid_hash));
	if (!ohe) {
		fprintf(stderr, "Malloc of ohe failed: %s\n", 
			strerror(errno));
		exit(1);
	}

	ohe->id = ost_fid->fid.lmm_object_id;
	ohe->ost_fid = ost_fid;
	
	HASH_ADD_INT(ost_hash, id, ohe);
}

void hash_update_fid(struct ost_fid *ost_fid) {
    struct ost_fid_hash *ohe; // ost hash entry
    uint64_t id = ost_fid->fid.lmm_object_id;

    if (!ost_hash) {
        fprintf(stderr, "can't update fid, fid not hashed\n");
        exit(1);
    }

    HASH_FIND_INT(ost_hash, &id, ohe);
    if (ohe == NULL) {
        fprintf(stderr, "can't update fid, fid not hashed\n");
        exit(1);
    }

    ohe->ost_fid = ost_fid;
}

struct ost_fid *hash_find_fid(uint64_t id)
{
	struct ost_fid_hash *ohe; // ost hash entry
	
	if (!ost_hash)
		return NULL;
	
	
	HASH_FIND_INT(ost_hash, &id, ohe);
	if (ohe == NULL)
		return NULL;
		
	return ohe->ost_fid;
}


